package com.woniuxy.redis.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * redis的核心配置类 通常是配置json转换的
 */
@Configuration
@EnableCaching //开启缓存
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 基本配置
     * @param connectionFactory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory ){
        RedisTemplate redisTemplate = new RedisTemplate();
//        设置连接工厂
        redisTemplate.setConnectionFactory(connectionFactory);
        //redis将传入的对象进行序列化和序列化
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //设置value的String类型
        redisTemplate.setValueSerializer(RedisSerializer.json());
        //hash类型
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        return redisTemplate;
    }
    //配置 springcache整合redis的配置
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        //默认缓存配置
        //通过jackson进行序列化配置 给SpringCache使用
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        return redisCacheConfiguration;
    }
}
